﻿using System;

using System.Collections.Generic;

using System.Windows;
using System.Windows.Controls;

using SwHelper.ModleView;

using SolidWorks.Interop.sldworks;
using SwUI.Modle;
using SolidWorks.Interop.swconst;
using Microsoft.Win32;
using System.IO;

namespace SwUI
{
    /// <summary>
    /// MainWin.xaml 的交互逻辑
    /// </summary>
    public partial class MainWin : Window
    {
        private object _trees = null;
        public SldWorks _swapp { get; set; }

        public MainWin(object _obj)
        {
            InitializeComponent();
            this._trees = _obj;
        }

        private void CreateComponentTree(NodeOfComponent parentNode, TreeViewItem parentItem, List<NodeOfComponent> nodes, List<NodeOfComponent> isContain){
            foreach (NodeOfComponent nodeOBj in nodes)
            {
                if (nodeOBj.parentNodeTag == parentNode.nodeTag)
                {
                    if (isContain.Contains(nodeOBj)) continue;
                    TreeViewItem _item = new TreeViewItem();
                    _item.Tag = nodeOBj.nodeTag;
                    _item.Header = nodeOBj.nodeName;
                    parentItem.Items.Add(_item);
                    isContain.Add(nodeOBj);
                }
            }
        }

        private void OnTreeViewItemSelect(object sender, RoutedPropertyChangedEventArgs<object>  e)
        {
            TreeViewItem _item = (TreeViewItem)this.treeView1.SelectedItem;

            NodeOfComponent _nodecomponent = _item.Tag as NodeOfComponent;
            Component2 _component = _nodecomponent.component;
            if (_component != null)
            {
                ModelDoc2 _doc = _swapp.IActiveDoc2;
                SelectionMgr selMrg = _doc.ISelectionManager;
                SelectData selData = selMrg.CreateSelectData();
                selData.Mark = 0;
                _component.Select4(false, selData, false);
            }

            List<DBTABLE> dvItemSources = new List<DBTABLE>();
            for (int i = 0; i < _item.Items.Count; i++)
            {
                DBTABLE _db = new DBTABLE();
                TreeViewItem _item2 = (TreeViewItem)_item.Items.GetItemAt(i);
                if (_item2 != null)
                {
                    NodeOfComponent nodecomponent2 = (NodeOfComponent)_item2.Tag;
                    Component2 component2 = nodecomponent2.component;
                    ModelDoc2 _doc2 = component2.GetModelDoc2();

                    object comPropNames = null;
                    object comPropTypes = null;
                    object comProperValues = null;
                    object comResolved = null;
                    object comProLink = null;
                    _doc2.Extension.CustomPropertyManager[""].GetAll3(ref comPropNames, ref comPropTypes, ref comProperValues, ref comResolved, ref comProLink);

                    //_doc2.Extension.CustomPropertyManager[""].GetAll(ref comPropNames, ref comPropTypes, ref comProperValues);
                    string[] propName = comPropNames as string[];
                    string[] propValue = comProperValues as string[];
                    if(propName != null)
                    {
                        for(int i_prop = 0; i_prop < propName.Length; i_prop++)
                        {
                            switch (propName[i_prop])
                            {
                                case "项目号": _db.DB_PARPROJECT = propValue[i_prop]; break;
                                case "名称": _db.DB_PARTNAME = propValue[i_prop];     break;
                                case "图号": _db.DB_PARTNUM = propValue[i_prop]; break;                               
                                default:break;
                            }
                        }
                    }
                    _db.DB_COUNT = nodecomponent2.nodeCount;
                }
                if(_db.DB_PARTNAME != null)
                {
                    dvItemSources.Add(_db);
                }
            }
            this.dgvList.ItemsSource = dvItemSources;             
        }

        private void MainWinLoad(object sender, RoutedEventArgs e)
        {
            this.dgvList.ItemsSource = new List<DBTABLE>();
            treeView1.SelectedItemChanged += OnTreeViewItemSelect;

            string templatePathStr = _swapp.GetUserPreferenceStringValue((int)swUserPreferenceStringValue_e.swFileLocationsDocumentTemplates);
            string[] templateList = templatePathStr.Split(new char[] { ';' });
            foreach(string templatePath in templateList)
            {
                string[] filestrlist = Directory.GetFiles(templatePath);
                foreach(string filestr in filestrlist)
                    if (filestr.Contains("draw.drwdot"))
                    {
                        this.textBlock1.Text = filestr;
                        break;
                    }
            }

            if (this._trees != null)
            {
                List<NodeOfComponent> isContain = new List<NodeOfComponent>();
                List<NodeOfComponent> listComponent = (List<NodeOfComponent>)this._trees;
                if (listComponent != null && listComponent.Count > 0)
                {
                    TreeViewItem rootTreeViewItem = new TreeViewItem();
                    rootTreeViewItem.Header = listComponent[0].nodeName;
                    rootTreeViewItem.Tag = listComponent[0].nodeTag;
                    this.treeView1.Items.Add(rootTreeViewItem);
                    rootTreeViewItem.ExpandSubtree();
                    
                    isContain.Add(listComponent[0]);

                    for (int i = 1; i < listComponent.Count; i++)
                    {
                        if (isContain.Contains(listComponent[i])) continue;
                        NodeOfComponent node = listComponent[i];
                        TreeViewItem _item = new TreeViewItem();
                        _item.Tag = node.nodeTag;
                        _item.Header = node.nodeName;
                        rootTreeViewItem.Items.Add(_item);
                        isContain.Add(listComponent[i]);
                        CreateComponentTree(node, _item, listComponent, isContain);
                    }

                    rootTreeViewItem.IsSelected = true;
                }
            }      
        }

        private void OpenSelTempateDlg(object sender, RoutedEventArgs e)
        {
            OpenFileDialog sfd = new OpenFileDialog();
            sfd.Filter = "图纸模板|*.drwdot";
            sfd.ShowDialog();
            string filePath = sfd.FileName;
            if (File.Exists(filePath))
            {
                this.textBlock1.Text = filePath;
            }
        }

        private void CreateDraw(object sender, RoutedEventArgs e)
        {
            string templatefile = this.textBlock1.Text;
            if (File.Exists(templatefile))
            {
                ModelDoc2 currentDoc = _swapp.ActiveDoc;
                string currentDocPath = currentDoc.GetPathName();

                DrawingDoc drawingDoc = _swapp.NewDocument(templatefile, 0, 0, 0);
                if(drawingDoc != null)
                {
                    ModelDoc2 _tdoc = drawingDoc as ModelDoc2;
                    _tdoc.SetUserPreferenceToggle((int)swUserPreferenceToggle_e.swDisplayOrigins, false);
                    
                    Sheet sheet1 = drawingDoc.Sheet["Sheet1"];
                    double sheet_x_w = 0.0, sheet_y_h = 0.0;
                    sheet1.GetSize(ref sheet_x_w, ref sheet_y_h);

                    View drawView1 = drawingDoc.CreateDrawViewFromModelView3(currentDocPath, "*前视", 0.2 * sheet_x_w, 0.75 * sheet_y_h, 0);


                    drawView1.InsertBomTable4(false, sheet_x_w-0.21124, 0.06277, (int)swBOMConfigurationAnchorType_e.swBOMConfigurationAnchor_BottomLeft, (int)swBomType_e.swBomType_TopLevelOnly, "默认", @"E:\SolidWorks\SwQueryAssemInfo\Part\mysldbomtbt.sldbomtbt", false, (int)swNumberingType_e.swNumberingType_Flat, false); 

                    _tdoc.EditRebuild3();
                }
                this.Close();
            }
            else
            {
                MessageBox.Show("请先选择一个有效的工程图模板");
            }

            
        }
    }


    public class Init
    {
        private static MainWin _win = null;
        
        public static void InitDlg(SldWorks _swapp)
        {
            if (_win == null)
            {

                ModelDoc2 modelDoc = _swapp.IActiveDoc2;
                AssemblyDoc assemblyDoc = modelDoc as AssemblyDoc;
                if (assemblyDoc != null)
                {
                    object[] componenes = assemblyDoc.GetComponents(true);

                    List<NodeOfComponent> lists = new List<NodeOfComponent>();

                    NodeOfComponent rootNode = new NodeOfComponent();
                    string topComName = modelDoc.GetTitle();
                    string[] names = topComName.Split(new char[] { '.' });
                    topComName = names[0];
                    rootNode.component = null;
                    rootNode.nodeTag = rootNode;
                    rootNode.nodeName = topComName;
                    rootNode.fullPath = modelDoc.GetPathName();
                    lists.Add(rootNode);

                    foreach (Component2 comobj in componenes)
                    {
                        NodeOfComponent node = new NodeOfComponent();
                        node.nodeName = comobj.Name2;
                        node.fullPath = comobj.GetPathName();
                        node.component = comobj;
                        node.parentNodeTag = rootNode.nodeTag;
                        node.nodeTag = node;
                        lists.Add(node);
                        NodeOfComponentIm.CreateComponentTree(node, lists);
                    }
                    NodeOfComponentIm.SortAndUnique(lists, out lists);

                    _win = new MainWin(lists);
                    _win.Closed += Close_Win;
                    _win._swapp = _swapp;
                    _win.Show();
                }else
                {
                    MessageBox.Show("该功能仅在装配中使用");
                }

            }
            else
            {
                try
                {
                    _win.Show();
                    _win.Activate();
                }
                catch(Exception e)
                {
                    MessageBox.Show(e.Message);
                }

            }
            
        }

        private static void Close_Win(object sender, EventArgs e)
        {
            _win = null;
        }
    }



    public class DBTABLE
    {
        public string DB_PARPROJECT { get; set; }
        public string DB_PARTNUM { get; set; }
        public string DB_PARTNAME { get; set; }
        public int DB_COUNT { get; set; }
    }
}
